package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhanghao
 * @date 2021/4/15 16:59
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Resource
    WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        //1.参数检查
        wmNewsPageReqDto.checkParam();
        //2.查询条件封装
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        //文章状态查询
        if (wmNewsPageReqDto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, wmNewsPageReqDto.getStatus());
        }
        //文章标题模糊查询
        //System.out.println(wmNewsPageReqDto.getKeyword());
        if (StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        }
        //频道条件查询
        if (wmNewsPageReqDto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        }
        //时间区间查询
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        }
        //查询当前登录用户
        Integer userId = WmThreadLocalUtils.getUser().getId();
        queryWrapper.eq(WmNews::getUserId, userId);
        //3.执行分页查询
        Page<WmNews> pageReq = new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());
        //按照文章创建时间降序排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> pageResult = page(pageReq, queryWrapper);
        //返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    /**
     * 保存或修改 自媒体文章
     *
     * @param wmNewsDto 文章数据
     * @param isSubmit  是否为提交 1 提交 0 草稿
     * @return
     */
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto, Short isSubmit) {
        // 1. 检查参数 封装成一个wmNews对象
        if (StringUtils.isBlank(wmNewsDto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH, "登录之后才能发表文章");
        }
        WmNews wmNews = new WmNews();
        // 将入参的属性 拷贝到 wmNews中
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        // 判断封面图片类型 是否为自动 如果自动 暂时设置为null
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 封面图片 入参为list<String>集合  转成 字符串  多个图片 ,号拼接
        List<String> images = wmNewsDto.getImages();
        if (images != null && !images.isEmpty()) {
            wmNews.setImages(
                    images.stream()
                            .map((url) -> url.replace(webSite, ""))
                            .collect(Collectors.joining(",")));
        }
        wmNews.setUserId(user.getId());
        // 2. 保存或修改wmNews
        saveOrUpdateWmNews(wmNews);
        if (isSubmit.equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)) {
            //  抽取 文章内容中 所保存的 所有图片路径 ==>  imageList
            List<String> materialUrlList = parseContentImages(wmNewsDto.getContent());
            // 3. 判断是提交还是草稿  如果提交需要保存内容和素材的关联关系
            if (materialUrlList != null && !materialUrlList.isEmpty()) {
                saveRelativeInfoForContent(materialUrlList, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
            }
            // 4. 判断是提交还是草稿  如果提交需要保存封面和素材的关联关系
            saveRelativeInfoForCover(materialUrlList, wmNews, wmNewsDto);
            Map map = new HashMap();
            map.put("wmNewsId", wmNews.getId());
            log.info("文章提交待审核成功，并发送kafka消息==》{}", wmNews.getId());
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        }
        return ResponseResult.okResult();
    }

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 1. 检查参数
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据id查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 3. 返回结果  host==> 添加访问前缀路径
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        // 1. 检查参数 判断是否登录
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH, "请登录之后在操作");
        }
        // 2. 根据id查询文章
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id).eq(WmNews::getUserId, user.getId()));
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到相关文章信息");
        }
        // 3. 如果文章状态为9 并且 上架状态 1 不可以删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable() == 1) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章已发布，请先下架后再删除");
        }
        // 4. 删除文章与素材的关联关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        // 5. 删除文章信息
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 1. 检查参数  判断id不能为空   enable ( 0   1 )
        if (dto.getId() == null || dto.getEnable() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (!dto.getEnable().equals(WemediaConstants.WM_NEWS_DOWN) && !dto.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "文章上下架参数错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH, "请先登录");
        }
        // 2. 根据id查询出文章数据
        WmNews one = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()).eq(WmNews::getUserId, user.getId()));
        if (one == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到该文章");
        }
        // 3. 判断文章状态是否为9(发布)   发布状态的文章才可以上下架
        if (!one.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR, "只有发布状态的文章才可以上下架");
        }
        // 4. 根据 id 修改 文章的 enable字段
        update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId()));
        if (one.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", one.getArticleId());
            map.put("enable", dto.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }
        return ResponseResult.okResult();
    }

    @Override
    public List<Integer> findRelease() {
        //查询文章状态为4、8，且发布时间小于当前时间
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .in(WmNews::getStatus, 4, 8)
                .le(WmNews::getPublishTime, new Date()));
        if (list != null && !list.isEmpty()) {
            return list.stream().map(WmNews::getId).collect(Collectors.toList());
        }
        return null;
    }

    @Resource
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
        //2.分页查询
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }
        Integer currentPage = dto.getPage();
        dto.setPage((currentPage - 1) * dto.getSize());
        //查看分页数据
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        //查询满足条件的总记录数
        long listCount = wmNewsMapper.findListCount(dto);
        //封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(currentPage, dto.getSize(), (int) listCount);
        pageResponseResult.setData(listAndPage);
        return pageResponseResult;
    }

    @Resource
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        // 1. 检查参数
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据id查询wm_news
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据不存在");
        }
        // 3. 查询WmUser
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        // 4. 返回给前端  ( webSite)
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        // 校验参数  dto  id
        if (dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据id查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据不存在");
        }
        // 修改 文章 status字段
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult();
    }

    /**
     * 保存  封面 与  素材的关联关系
     *
     * @param materialUrlList 图片url列表
     * @param wmNews
     * @param wmNewsDto
     */
    private void saveRelativeInfoForCover(List<String> materialUrlList, WmNews wmNews, WmNewsDto wmNewsDto) {
        // 1. 获取请求中的文章封面图片列表
        List<String> images = wmNewsDto.getImages();
        // 2. 判断当前封面图片类型是否是  自动生成
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (materialUrlList != null && !materialUrlList.isEmpty()) {
                // 内容图片列表不为空
                int imgNum = materialUrlList.size();
                if (imgNum <= 2) {
                    wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                    images = materialUrlList.stream().limit(1).collect(Collectors.toList());
                } else {
                    wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                    images = materialUrlList.stream().limit(3).collect(Collectors.toList());
                }
                wmNews.setImages(images.stream()
                        .map(url -> url.replace(webSite, ""))
                        .collect(Collectors.joining(",")));
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            // 保存
            updateById(wmNews);
        }
        if (images != null && !images.isEmpty()) {
            images = images.stream()
                    .map(url -> url.replace(webSite, ""))
                    .collect(Collectors.toList());
            // 保存封面图片  与  素材的关联关系
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    private void saveRelativeInfoForContent(List<String> materialUrlList, Integer newId, Short wmContentReference) {
        saveRelativeInfo(materialUrlList, newId, wmContentReference);
    }


    /**
     * 保存关联关系的方法
     *
     * @param materialUrlList 素材图片路径
     * @param newId           文章ID
     * @param type            引用类型 0 内容引用     1 封面引用
     */
    private void saveRelativeInfo(List<String> materialUrlList, Integer newId, Short type) {
        // 1. 根据图片路径 及 登录用户  查询出 相关素材ID列表
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materialUrlList)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
        );
        if (wmMaterials == null || wmMaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "查询素材信息失败");
        }
        // 2. 检查所有素材是否全部存在   wmMaterials ==> 转为Map ==>   key: url     value: id
        List<Integer> materialIdList = new ArrayList<>();
        Map<String, Integer> urlAndIdMap = wmMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String materialUrl : materialUrlList) {
            if (urlAndIdMap.get(materialUrl) == null) {
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "素材数据不存在");
            }
            materialIdList.add(urlAndIdMap.get(materialUrl));
        }
        // 3. 得到的素材ID  和  文章ID  及   引用类型  保存关联关系
        wmNewsMaterialMapper.saveRelations(materialIdList, newId, type);
    }

    /**
     * 抽取文章内容中 所包含的 所有素材路径
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        // 将 json字符串转为 map集合
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        return contentList.stream()
                .filter(this::isImage)
                .map((map) -> (String) map.get("value"))
                .map(imageUrl -> imageUrl.replace(webSite, ""))
                .collect(Collectors.toList());
    }

    /**
     * 判断 是否为图片类型
     *
     * @param map
     * @return
     */
    private boolean isImage(Map map) {
        return map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE);
    }

    /**
     * 保存 或 修改文章的 方法
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (wmNews.getId() == null) {
            // 添加文章
            wmNews.setCreatedTime(new Date());
            wmNews.setEnable((short) 1);
            wmNews.setSubmitedTime(new Date());
            save(wmNews);
        } else {
            // 删除素材 和 文章的关联关系
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId())
            );
            // 修改文章
            updateById(wmNews);
        }
    }
}